/*
 * Copyright 2019 xiaomaoguai.com All right reserved. This software is the
 * confidential and proprietary information of xiaomaoguai.com ("Confidential
 * Information"). You shall not disclose such Confidential Information and shall
 * use it only in accordance with the terms of the license agreement you entered
 * into with xiaomaoguai.com.
 */

package com.xiaomaoguai.core.next.nacos.ribbon;

import app.myoss.cloud.core.constants.DeployEnvEnum;
import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.ribbon.NacosServer;
import com.alibaba.cloud.nacos.ribbon.NacosServerList;
import com.alibaba.nacos.api.naming.pojo.Instance;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import static com.xiaomaoguai.core.next.nacos.constants.NacosDiscoveryConstants.META_SERVICE_DOMAIN;

/**
 * 查询 "Nacos服务实例" 集合API
 *
 * @author chenyao
 * @since 2019年6月19日 下午6:14:21
 */
public class ZaNacosServerList extends NacosServerList {
    private NacosDiscoveryProperties discoveryProperties;

    /**
     * 创建查询服务实例的对象
     *
     * @param discoveryProperties Nacos服务发现配置属性
     */
    public ZaNacosServerList(NacosDiscoveryProperties discoveryProperties) {
        super(discoveryProperties);
        this.discoveryProperties = discoveryProperties;
    }

    @Override
    public List<NacosServer> getInitialListOfServers() {
        return getServers();
    }

    @Override
    public List<NacosServer> getUpdatedListOfServers() {
        return getServers();
    }

    private List<NacosServer> getServers() {
        String serviceId = getServiceId();
        try {
            List<Instance> instances = discoveryProperties.namingServiceInstance().selectInstances(serviceId, true);
            return instancesToServerList(instances);
        } catch (Exception e) {
            throw new IllegalStateException("Can not get service instances from nacos, serviceId=" + serviceId, e);
        }
    }

    private List<NacosServer> instancesToServerList(List<Instance> instances) {
        if (CollectionUtils.isEmpty(instances)) {
            return Collections.emptyList();
        }
        List<NacosServer> result = new ArrayList<>(instances.size());
        if (DeployEnvEnum.isTest()) {
            // 如果是测试环境，当前服务部署在 boom3 中，只能调用 boom3 中的 IP，不能调用办公网络的 IP
            for (Instance instance : instances) {
                Map<String, String> metadata = instance.getMetadata();
                if (metadata.containsKey(META_SERVICE_DOMAIN)) {
                    result.add(new ZaNacosServer(instance));
                }
            }
        } else {
            for (Instance instance : instances) {
                result.add(new ZaNacosServer(instance));
            }
        }
        return result;
    }

}
